package com.sweet.logging.logger;

import com.sweet.logging.appender.Appender;
import com.sweet.logging.appender.RemoteAppender;
import com.sweet.logging.appender.StdoutAppender;

import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

/**
 * Sweet 日志管理器
 *      负责读取配置文件，初始化各个部件
 *
 * @author xiexiaofeng
 * @version 1.0     2017年09月08日  10点55分
 */
public class SweetLogManager
{
    private static final String CONFIG_FILE_NAME = "sweet-logging.properties";

    private static List<Appender> appenders = new ArrayList<>();

    private static int level; // 默认日志级别INFO
    static
    {
        // 日志配置文件
        Properties properties = new Properties();
        try
        {
            // 加载配置文件
            properties.load(SweetLogManager.class.getClassLoader().getResourceAsStream(CONFIG_FILE_NAME));
            String appendersConfig = properties.getProperty("sweet.appender.use");
            String[] appendersArray = appendersConfig.contains(",") ? appendersConfig.split(",", -2) : (new String[]{appendersConfig});
            for (String appenderName : appendersArray)
            {
                switch (appenderName)
                {   // 加载 Appender， Appender 负责处理写日志事件
                    case StdoutAppender.CONFIG_NAME : appenders.add(new StdoutAppender());break;
                    case RemoteAppender.CONFIG_NAME : appenders.add(new RemoteAppender(properties));break;
                    default:appenders.add(new StdoutAppender());
                }
            }
            Runtime.getRuntime().addShutdownHook(new Thread(()->{
                for (Appender appender : appenders)
                {
                    if (appender instanceof RemoteAppender)
                        ((RemoteAppender) appender).close(); // 关闭连接
                }
            }));
            String logLevel = properties.getProperty("sweet.level"); // 日志输出级别
            if (logLevel != null && !"".equals(logLevel.trim()))
                level = LoggingLevel.getCodeByName(logLevel);

        } catch (Exception e)
        {
            throw new RuntimeException("read config file error, file name:" + CONFIG_FILE_NAME, e);
        }
    }

    public static SweetLogger getRootLogger()
    {
        return new DefaultSweetLogger(level);
    }

    public static SweetLogger getLogger(final String name)
    {
        return new DefaultSweetLogger(level, name, appenders);
    }

}
